﻿#include "WSListener.h"
#include "BaseCmd.h"
#include "SetConfigCmd.h"
#include "AddModelCmd.h"
#include "SetModelCmd.h"
#include "DelModelCmd.h"
#include "AddDeviceCmd.h"
#include "SetDeviceCmd.h"
#include "DelDeviceCmd.h"
#include "AddSceneCmd.h"
#include "SetSceneCmd.h"
#include "DelSceneCmd.h"
#include "../log/SysLog.h"
#include "../util/SystemHelper.h"
#include "../service/ConfigService.h"
#include "../service/ModelService.h"
#include "../service/DeviceService.h"
#include "../service/SceneService.h"
#include "../AiBox.h"

WSListener::WSListener(std::mutex& writeMutex)
	: m_writeMutex(writeMutex)
{

}

void WSListener::onPing(const WebSocket& socket, const oatpp::String& message) {
	OATPP_LOGD(TAG, "onPing");
	std::lock_guard<std::mutex> lock(m_writeMutex);
	socket.sendPong(message);
}

void WSListener::onPong(const WebSocket& socket, const oatpp::String& message) {
	OATPP_LOGD(TAG, "onPong");
}

void WSListener::onClose(const WebSocket& socket, v_uint16 code, const oatpp::String& message) {
	OATPP_LOGD(TAG, "onClose code=%d", code);
}

void WSListener::readMessage(const WebSocket& socket, v_uint8 opcode, p_char8 data, oatpp::v_io_size size) {
	// 消息传输结束
	if(size == 0) {
		// 获取消息帧
		auto wholeMessage = m_messageBuffer.toString();
		m_messageBuffer.setCurrentPosition(0);
		std::string content = wholeMessage.getValue("");
		m_messageBuffer.reset();
		LOG_INFO("[websocket] receive message: {}", content);
		// 消息处理
		this->processMessage(content);
	// 缓存消息帧
	} else if(size > 0) {
		m_messageBuffer.writeSimple(data, size);
	}
}

void WSListener::processMessage(std::string message)
{
	// 解析json
	BaseCmd baseCmd;
	if (!baseCmd.Parse(message))
	{
		LOG_WARN("invalid web socket message:{}", message);
		return ;
	}

	// 系统重启
	if (SC_CMD_REBOOT == baseCmd.GetCmd())
	{
		SystemHelper::get_mutable_instance().Reboot();
	}
	// 获取配置
	else if (SC_CMD_GET_CONFIG == baseCmd.GetCmd())
	{
		
	}
	// 系统配置
	else if (SC_CMD_SET_CONFIG == baseCmd.GetCmd())
	{
		SetConfigCmd setConfigCmd;
		setConfigCmd.Parse(message);

		ConfigService configService;
		std::vector<ConfigInfo> configs = setConfigCmd.GetConfigs();
		for (size_t index = 0; index < configs.size(); ++index)
		{
			configService.UpdateByKey(configs[index]);
		}
	}
	// 添加模型
	else if (SC_CMD_ADD_MODEL == baseCmd.GetCmd())
	{
		AddModelCmd addModelCmd;
		if (!addModelCmd.Parse(message))
		{
			LOG_WARN("parse or download model failed, ignore add model.");
			return;
		}
		ModelInfo model = addModelCmd.GetModel();
		if (!model.GetId().empty())
		{
			bool exis = false;
			ModelService modelService;
			if (modelService.Exist(model.GetId(), exis) && !exis)
			{
				modelService.Add(model);
			}
		}
	}
	// 修改模型
	else if (SC_CMD_SET_MODEL == baseCmd.GetCmd())
	{
		SetModelCmd setModelCmd;
		if (!setModelCmd.Parse(message))
		{
			LOG_WARN("parse or download model failed, ignore update model.");
			return;
		}

		ModelService modelService;
		ModelInfo model = setModelCmd.GetModel();
		if (!model.GetId().empty())
		{
			modelService.Update(model);
		}
	}
	// 删除模型
	else if (SC_CMD_DEL_MODEL == baseCmd.GetCmd())
	{
		DelModelCmd delModelCmd;
		if (!delModelCmd.Parse(message))
		{
			LOG_WARN("parse model failed, ignore delete model.");
			return;
		}

		std::string model_id = delModelCmd.GetModelId();
		ModelInfo model;
		model.SetId(model_id);

		ModelService modelService;
		if (modelService.Find(model))
		{
			// 删除文件
			std::string path = SystemHelper::get_mutable_instance().GetFileSavePath(model.GetId() + ".onnx");
			Box::get_mutable_instance().GetFileClear()->AddFile(path);
			// 删除模型
			modelService.Delete(model);
		}		
	}
	// 添加设备
	else if (SC_CMD_ADD_DEVICE == baseCmd.GetCmd())
	{
		AddDeviceCmd addDeviceCmd;
		if (!addDeviceCmd.Parse(message))
		{
			LOG_WARN("parse device failed, ignore device add.");
			return;
		}

		DeviceInfo device = addDeviceCmd.GetDevice();
		if (!device.GetId().empty())
		{
			DeviceService deviceService;
			deviceService.Add(device);
		}
	}
	// 修改设备
	else if (SC_CMD_SET_DEVICE == baseCmd.GetCmd())
	{
		SetDeviceCmd setDeviceCmd;
		if (!setDeviceCmd.Parse(message))
		{
			LOG_WARN("parse device failed, ignore device update.");
			return;
		}

		DeviceInfo device = setDeviceCmd.GetDevice();
		if (!device.GetId().empty())
		{
			DeviceService deviceService;
			deviceService.Update(device);
		}
	}
	// 删除设备
	else if (SC_CMD_DEL_DEVICE == baseCmd.GetCmd())
	{
		DelDeviceCmd delDeviceCmd;
		if (!delDeviceCmd.Parse(message))
		{
			LOG_WARN("parse device failed, ignore device delete.");
			return;
		}

		std::string device_id = delDeviceCmd.GetDeviceId();
		if (!device_id.empty())
		{
			DeviceInfo device;
			device.SetId(device_id);

			DeviceService deviceService;
			deviceService.Delete(device);

			Box::get_mutable_instance().GetFileClear()->AddDevice(device_id);
		}
	}
	// 添加场景
	else if (SC_CMD_ADD_SCENE == baseCmd.GetCmd())
	{
		AddSceneCmd addSceneCmd;
		if (!addSceneCmd.Parse(message))
		{
			LOG_WARN("parse scene failed, ignore scene add.");
			return;
		}

		SceneInfo scene = addSceneCmd.GetScene();
		if (!scene.GetModel().empty())
		{
			SceneService sceneService;
			sceneService.Add(scene);
		}
	}
	// 修改场景
	else if (SC_CMD_SET_SCENE == baseCmd.GetCmd())
	{
		SetSceneCmd setSceneCmd;
		if (!setSceneCmd.Parse(message))
		{
			LOG_WARN("parse scene failed, ignore scene update.");
			return;
		}

		SceneInfo scene = setSceneCmd.GetScene();
		if (!scene.GetModel().empty())
		{
			SceneService sceneService;
			sceneService.Update(scene);
		}
	}
	// 删除场景
	else if (SC_CMD_DEL_SCENE == baseCmd.GetCmd())
	{
		DelSceneCmd delSceneCmd;
		if (!delSceneCmd.Parse(message))
		{
			LOG_WARN("parse scene failed, ignore scene delete.");
			return;
		}

		std::string scene_id = delSceneCmd.GetSceneId();
		if (!scene_id.empty())
		{
			SceneInfo scene;
			scene.SetId(scene_id);

			SceneService sceneService;
			sceneService.Delete(scene);
		}
	}
	// 播放视频
	else if (SC_CMD_PLAY_VIDEO == baseCmd.GetCmd())
	{
	}
	// 停止视频
	else if (SC_CMD_STOP_VIDEO == baseCmd.GetCmd())
	{
	}
	// 远程抓拍
	else if (SC_CMD_RMOTE_CAP == baseCmd.GetCmd())
	{
	}
	// 开始录像
	else if (SC_CMD_START_REC == baseCmd.GetCmd())
	{
	}
	// 停止录像
	else if (SC_CMD_STOP_REC == baseCmd.GetCmd())
	{
	}
}